package main

import (
	"context"
	"demo1/message"
	"encoding/json"
	"fmt"
	 restful "github.com/emicklei/go-restful/v3"
	"github.com/micro/go-micro/v2/client"
	"github.com/micro/go-micro/v2/web"
)
/**
rpc通信代理http请求
运行步骤：
micro api --handler=http
go run server.go
go run rest.go
注意serverd端的服务名称必须为：
go.micro.srv.http path
注意client端的服务名称必须为：
go.micro.api.http path
 */

var studentClient message.SetudenService
type User struct{}
func (user *User) GetUser(request *restful.Request,response *restful.Response){
	name := request.PathParameter("name")
	fmt.Println(name)
	//rpc调用远程服务
	student,err := studentClient.GetStudent(context.Background(),&message.StudentRequest{Name:name})
	if err!=nil{
		response.Write([]byte("该学生不存在！"))
	}else {
		result,_ := json.Marshal(student)
		response.Write(result)
	}
}

func main(){
	//创建client端微服务对象,使用web包的NewService()创建服务对象
	service := web.NewService(web.Name("go.micro.api.st"),web.Version("v1.0.0"))
	service.Init()
	//获取student远程服务的api client端
	studentClient = message.NewSetudenService("go.micro.srv.st",client.DefaultClient)

	ws := new(restful.WebService)
	user := new(User)
	//http:localhost:8080/st/
	ws.Path("/st")
	ws.Consumes(restful.MIME_XML, restful.MIME_JSON)
	ws.Produces(restful.MIME_JSON, restful.MIME_XML)
	//http:localhost:8080/st/ztind
	ws.Route(ws.GET("/{name}").To(user.GetUser))
	//http router container
	wc := restful.NewContainer()
	wc.Add(ws)

	//处理请求
	service.Handle("/",wc)

	//开启路由监听服务
	if err := service.Run();err!=nil{
		panic(err)
	}
}
